<?php

namespace App\Http\Controllers\CRM;

use App\Helper\ApiResponseHelper;
use App\Helper\NotificationRulesHelper;
use App\Http\Controllers\Controller;
use App\Http\Resources\CRM\StoreNotificationResource;
use App\Models\StoreNotification;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserNotificationController extends Controller
{
    public function getRules(Request $request)
    {
        $user = $request->user_id ? User::find($request->user_id) : null;
        $rules = NotificationRulesHelper::getRules($user);

        return ApiResponseHelper::json($rules);
    }

    public function getNotifications()
    {
        /**
         * @var User $user
         */
        $user = Auth::user();

        $rules = $user->notificationRules;
        if (empty($rules))
            return StoreNotificationResource::collection(StoreNotification::where('store_id', -1)->paginate());

        $query = StoreNotification::where('store_id', $user->store_id)->latest()->with(['operator']);
        $query->where(function ($query) use ($rules) {
            foreach ($rules as $rule) {
                $query->orWhere(function ($query) use ($rule) {
                    $query->where('type', $rule->type)
                        ->where('notification_name', $rule->notification_name);
                });
            }
        });

        return StoreNotificationResource::collection($query->paginate());
    }

    public function getNotificationInfo(StoreNotification $notification)
    {
        $notification->load([
            'operator'
        ]);
        return new StoreNotificationResource($notification);
    }

    public function agree(StoreNotification $notification)
    {
        $notification->agree();

        return ApiResponseHelper::json([]);
    }

    public function refuse(StoreNotification $notification)
    {
        $notification->refuse();

        return ApiResponseHelper::json([]);
    }
}
